<template>
  <view class="container">
    <!-- Header with search and add button -->
    <view class="header">
      <uni-search-bar v-model="searchTerm" placeholder="搜索用户" class="search-bar"></uni-search-bar>
      <uni-button type="primary" size="mini" @click="fetchUsers">搜索</uni-button>
      <uni-button type="primary" size="mini" @click="openAddPopup" style="margin-left: 10px;">新增用户</uni-button>
    </view>

    <!-- User list table -->
    <uni-table :border="true">
      <uni-tr>
        <uni-th align="center">用户名</uni-th>
        <uni-th align="center">是否主账号</uni-th>
        <uni-th align="center">门店数量限制</uni-th>
        <uni-th align="center">创建时间</uni-th>
        <uni-th align="center">更新时间</uni-th>
        <uni-th align="center">操作</uni-th>
      </uni-tr>
      <uni-tr v-for="user in users" :key="user.id">
        <uni-td align="center">{{ user.username }}</uni-td>
        <uni-td align="center">{{ user.is_main_account ? '是' : '否' }}</uni-td>
        <uni-td align="center">{{ user.store_limit }}</uni-td>
        <uni-td align="center">{{ user.created_at }}</uni-td>
        <uni-td align="center">{{ user.updated_at }}</uni-td>
        <uni-td align="center">
          <uni-button type="default" size="mini" @click="openEditPopup(user)">编辑</uni-button>
          <uni-button type="error" size="mini" @click="openDeletePopup(user)">删除</uni-button>
        </uni-td>
      </uni-tr>
    </uni-table>

    <!-- Pagination -->
    <view style="margin-top: 20px;">
      <uni-pagination :total="totalPages" @change="handlePageChange"></uni-pagination>
    </view>

    <!-- Popup for adding/editing a user -->
    <uni-popup ref="editPopup" type="center">
      <view class="popup-container">
        <h3>{{ currentUser.id ? '编辑用户' : '新增用户' }}</h3>
        <view class="form-row">
          <label>用户名：</label>
          <input v-model="currentUser.username" class="input-field" />
        </view>
        <view class="form-row">
          <label>密码：</label>
          <input v-model="currentUser.password" class="input-field" type="password" />
        </view>
        <view class="form-row">
          <label>是否主账号：</label>
          <view class="radio-group">
            <radio-group @change="radioChange" class="gender-options" :value="currentUser.is_main_account">
              <label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in items" :key="item.value">
                <radio :value="item.value" :checked="item.value == currentUser.is_main_account" />{{ item.name }}
              </label>
            </radio-group>
          </view>
        </view>
        <view class="form-row" v-if="currentUser.is_main_account == 1">
          <label>门店数量限制：</label>
          <input v-model="currentUser.store_limit" class="input-field" type="number" />
        </view>
        <view class="button-group">
          <uni-button type="primary" size="small" @click="saveUser">保存</uni-button>
          <uni-button type="default" size="small" @click="closePopup">取消</uni-button>
        </view>
      </view>
    </uni-popup>

    <!-- Popup for confirming deletion -->
    <uni-popup ref="deletePopup" type="center">
      <view class="popup-container">
        <h3>确认删除</h3>
        <text>确定要删除 "{{ currentUser.username }}" 吗？</text>
        <view class="button-group">
          <uni-button type="error" size="small" @click="confirmDelete">删除</uni-button>
          <uni-button type="default" size="small" @click="closePopup">取消</uni-button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        searchTerm: '',
        users: [],
        currentUser: {
          is_main_account: 0, // 初始化为0
          store_limit: 0 // 初始化为0
        },
        totalPages: 1,
        currentPage: 1,
        pageSize: 10, // 添加分页大小
        current: 0, // 默认选中否
        items: [
          { name: "否", value: "0" },
          { name: "是", value: "1" }
        ],
      };
    },
    methods: {
      radioChange(e) {
        this.currentUser.is_main_account = e.detail.value;
      },

      async fetchUsers() {
        const res = await this.$myRuquest({
          url: '/index/plugin.users/get_users',
          method: 'POST',
          data: {
            page: this.currentPage,
            pageSize: this.pageSize,
            searchQuery: this.searchTerm
          }
        });
        if (res.data.code === 200) {
          this.users = res.data.data;
          this.totalPages = res.data.totalPages;
        } else {
          uni.showToast({
            title: res.data.info,
            duration: 2000,
            icon: 'none',
          });
        }
      },
      openAddPopup() {
        this.currentUser = {
          is_main_account: 0, // 初始化为0
          store_limit: 0 // 初始化为0
        };
        this.$refs.editPopup.open();
      },
      openEditPopup(user) {
        this.currentUser = {
          ...user
        };
        this.current = this.items.findIndex(item => item.value == user.is_main_account); // 设置当前选中的单选按钮
        this.$refs.editPopup.open();
      },
      closePopup() {
        this.$refs.editPopup.close();
        this.$refs.deletePopup.close();
      },
      async saveUser() {
        const res = await this.$myRuquest({
          url: '/index/plugin.users/save_user',
          method: 'POST',
          data: {
            ...this.currentUser,
            is_main_account: this.currentUser.is_main_account,
            pid: 0,
            shop_id: 1,
            storeIndex: 0
          } // 直接传递currentUser对象
        });
        if (res.data.code === 200) {
          this.fetchUsers(); // 重新获取用户列表
          this.closePopup();
        } else {
          uni.showToast({
            title: res.data.info,
            duration: 2000,
            icon: 'none',
          });
        }
      },
      openDeletePopup(user) {
        this.currentUser = {
          ...user
        };
        this.$refs.deletePopup.open();
      },
      async confirmDelete() {
        const res = await this.$myRuquest({
          url: '/index/plugin.users/delete_user',
          method: 'POST',
          data: {
            id: this.currentUser.id,
          }
        });
        if (res.data.code === 200) {
          this.fetchUsers();
          this.closePopup();
        } else {
          uni.showToast({
            title: res.data.info,
            duration: 2000,
            icon: 'none',
          });
        }
      },
      handlePageChange(e) {
        this.currentPage = e.detail.current;
        this.fetchUsers();
      },
    },
    mounted() {
      this.fetchUsers();
    },
  };
</script>

<style>
  .container {
    padding: 20px;
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .search-bar {
    flex: 1;
    margin-right: 15px;
  }

  .popup-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  }

  .form-row {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
  }

  .radio-group {
    display: flex;
    justify-content: space-between;
  }

  label {
    width: 80px;
    color: #666;
    margin-right: 10px;
  }

  .input-field {
    flex: 1;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    outline: none;
  }

  .button-group {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
  }
</style>
